﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Globalization;
using System.Web.Security;
using System.IO;

namespace Warehouse.Web.AppCode
{
    public static class WebUtil
    {
        public static void WriteJsonError(HttpContext context, object err)
        {
            WriteJson(context, new JsonResponse()
            {
                Code = JsonResponseCode.ERROR,
                Error = err
            });
        }

        public static void WriteJsonResult(HttpContext context, object result)
        {
            WriteJson(context, new JsonResponse()
            {
                Code = JsonResponseCode.SUCCEED,
                Result = result
            });
        }

        public static void WriteJson(HttpContext context, object obj)
        {
            context.Response.ContentType = "application/json";
            context.Response.Write(new JavaScriptSerializer().Serialize(obj));
            //context.Response.Flush();
        }

        public static DateTime ParseDateTime(string dateString)
        {
            if (dateString.IndexOf(".") > 0)
            {
                return DateTime.ParseExact(dateString, "yyyy-M-d H:m:s.f", CultureInfo.InvariantCulture, DateTimeStyles.None);
            }
            else if (dateString.IndexOf(" ") > 0)
            {
                return DateTime.ParseExact(dateString, "yyyy-M-d H:m:s", CultureInfo.InvariantCulture, DateTimeStyles.None);
            }
            else
            {
                return DateTime.ParseExact(dateString, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.None);
            }
        }

        public static string GetVirtualPath(string physicalfile)
        {
            if (!string.IsNullOrEmpty(physicalfile) && Path.IsPathRooted(physicalfile))
            {
                string root = HttpContext.Current.Server.MapPath("~");
                if (!root.EndsWith("\\"))
                {
                    root += "\\";
                }

                if (physicalfile.IndexOf(root, 0, StringComparison.CurrentCultureIgnoreCase) == 0)
                {
                    return "~/" + physicalfile.Substring(root.Length).Replace("\\", "/");
                }

            }
            return null;
        }
    }

    public class JsonResponse
    {
        public JsonResponseCode Code { get; set; }
        public object Error { get; set; }
        public object Result { get; set; }
    }

    public enum JsonResponseCode
    {
        UNKOWN = 0,
        UNAUTHORIZED = 1,
        SUCCEED = 2,
        ERROR = 3
    }
}
